<?php
/**
 * (logic) 运营报表-试算产品利润率
 */
namespace App\Logic\Operation;

use App\Models\Basics\AmazonCountry;
use App\Models\Basics\ExchangeRate;
use App\Models\Basics\SysICountry;
use App\Models\Basics\Transport;
use App\Models\Operation\ProfitSku;
use App\Models\Operation\ProfitTry;
use Illuminate\Support\Facades\DB;
class CalculateProfitTry
{
    /**
     * 计算试算产品利润率
     */
    public static function handle()
    {
        $area = [];
        $rate = [];
        $transportFee = [];
        ProfitTry::query()
            ->orderBy('id')
            ->chunk(800, function ($items) use (&$rate,&$area,&$transportFee){
                DB::beginTransaction();
                try{
                    foreach ($items as $item){
                        if(!array_key_exists($item->country_id,$rate)){
                            $currencyCode = AmazonCountry::getCurrencyCodeByCountryId($item->country_id);
                            $rate[$item->country_id] = ExchangeRate::getRateOddsToRMB($currencyCode,time());
                        }
                        $item->rate_odds = $rate[$item->country_id];
                        if(!array_key_exists($item->country_id,$area)){
                            $area[$item->country_id] = SysICountry::getAreaIdByCountryId($item->country_id);
                        }
                        $areaId = $area[$item->country_id];
                        $key = $areaId .'_'. $item->transport;
                        if(!array_key_exists($key,$transportFee)){
                            $transportFee[$key] = Transport::getShipmentFee($areaId,$item->transport);
                        }
                        $tpl = round($item->tpl_rmb / $item->rate_odds,3);
                        $item->head_cost = round($item->weight * $transportFee[$key] / $item->rate_odds,3);
                        $item->cost = ProfitSku::getCost($tpl,$item->sale_price,$item->head_cost,$item->fba_fee,$item->commission,$item->return,$item->vat);
                        $item->profit = round($item->sale_price - $item->cost,3);
                        $item->profit_rate = !$item->sale_price ? 0 : round($item->profit / $item->sale_price,3);
                        $item->save();
                    }
                    DB::commit();
                }catch (\Exception $e){
                    DB::rollBack();
                    report($e);
                }
        });
    }
}
